package cn.itsource.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.itsource.api.LoginRemoteApi;
import cn.itsource.constants.CacheConstants;
import cn.itsource.constants.ErrorCode;
import cn.itsource.constants.RConst;
import cn.itsource.domain.dto.DriverSettingRedisDto;
import cn.itsource.mapper.DriverMapper;
import cn.itsource.mapper.DriverSettingMapper;
import cn.itsource.pojo.domain.Driver;
import cn.itsource.pojo.domain.DriverSetting;
import cn.itsource.pojo.domain.Login;
import cn.itsource.pojo.dto.DriverOnLineDto;
import cn.itsource.pojo.dto.DriverRegisterDto;
import cn.itsource.result.JSONResult;
import cn.itsource.service.IDriverService;
import cn.itsource.service.WechatTemplate;
import cn.itsource.utils.IdUtil;
import cn.itsource.utils.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 司机对象 服务实现类
 * </p>
 *
 * @author zong
 * @since 2024-08-31
 */
@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements IDriverService {
    @Autowired
    private WechatTemplate wechatTemplate;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private LoginRemoteApi loginRemoteApi;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private DriverSettingMapper driverSettingMapper;
    @Override
    // @Transactional
    @GlobalTransactional(name = "driver-wechat-register",rollbackFor = Exception.class)
    public JSONResult driverRegister(DriverRegisterDto dto) {
        String openId = wechatTemplate.getOpenId(dto.getCode());
        // String accessToken = wechatTemplate.getAccessToken();
        // String userPhone = wechatTemplate.getUserPhone(dto.getPhoneCode(), accessToken);
        //构建查询条件
        // QueryWrapper<Driver> wrapper = new QueryWrapper<Driver>().eq("openId", openId);
        LambdaQueryWrapper<Driver> wrapper = new LambdaQueryWrapper<Driver>()
                .eq(Driver::getOpenId,openId)
                .select(Driver::getOpenId);
        Driver driver1 = driverMapper.selectOne(wrapper);
        if(driver1 == null){
            System.out.println(openId);
            Driver driver = new Driver();
            driver.setId(IdUtil.getId());
            driver.setCreateTime(new Date());
            driver.setOpenId(openId);
            // driver.setPhone(userPhone);
            super.save(driver);
            //同步到uaa里面
            loginRemoteApi.create(getLogin(driver, openId));
            return JSONResult.success();
        }
        // throw new GlobalException(ErrorCode.PARAM_PHONE_EXIST);
        return JSONResult.error(ErrorCode.PARAM_PHONE_EXIST);
    }

    @Override
    public JSONResult online(DriverOnLineDto onLineDto) {
        //1.保存当前司机的坐标
        GeoOperations<String, Object> geo = redisTemplate.opsForGeo();
        Point point = new Point(onLineDto.getLongitude(),onLineDto.getLatitude());
        geo.add(CacheConstants.DRIVER_POINT,point, StpUtil.getLoginIdAsLong());
        redisTemplate.expire(CacheConstants.DRIVER_POINT+StpUtil.getLoginIdAsLong()
                ,RConst.Num.BASE_LONG_5, TimeUnit.MINUTES);
        //2.保存当前司机的配置  redis
        DriverSetting setting = driverSettingMapper.selectById(StpUtil.getLoginIdAsLong());
        DriverSettingRedisDto driverSettingRedisDto = new DriverSettingRedisDto();
        BeanUtils.copyProperties(setting,driverSettingRedisDto);
        redisTemplate.opsForValue()
                .set(CacheConstants.DRIVER_POINT_SETTING+StpUtil.getLoginIdAsLong(),driverSettingRedisDto);
        return JSONResult.success();
    }

    @Override
    public JSONResult refresh(DriverOnLineDto onLineDto) {
        //1.保存当前司机的坐标
        GeoOperations<String, Object> geo = redisTemplate.opsForGeo();
        Point point = new Point(onLineDto.getLongitude(),onLineDto.getLatitude());
        Long add = geo.add(CacheConstants.DRIVER_POINT, point, StpUtil.getLoginIdAsLong());
        if(add == 1){
            redisTemplate.expire(CacheConstants.DRIVER_POINT+StpUtil.getLoginIdAsLong()
                    ,RConst.Num.BASE_LONG_5, TimeUnit.MINUTES);
        }
        return JSONResult.success();
    }

    @Override
    public JSONResult offline() {
        redisTemplate.opsForGeo().remove(CacheConstants.DRIVER_POINT,StpUtil.getLoginIdAsLong());
        redisTemplate.delete(CacheConstants.DRIVER_POINT_SETTING+StpUtil.getLoginIdAsLong());
        return JSONResult.success();
    }



    /**
     * 构建一个login
     * @param driver
     * @param openId
     * @return
     */
    private static Login getLogin(Driver driver, String openId) {
        Login login = new Login();
        login.setId(driver.getId());
        login.setUsername(NameUtil.getName());
        login.setPassword("123456");
        login.setType(RConst.Num.INT_1);
        login.setAdmin(RConst.Num.INT_0);
        login.setNickName(login.getUsername());
        login.setOpenId(openId);
        login.setName(login.getUsername());
        login.setCreateTime(new Date());
        // login.setPhone(driver.getPhone());
        return login;
    }
}
